# -*- coding: utf-8 -*-
#数据库操作类

import sys
import pymysql
# sys.path.append('..')
import config.db_conf as dbConf

class Db():

    sql = ''
    table_name= ''
    where_str = ''
    fields_str = ''

    def __init__(self):
        # print('连接数据库')
        self.db = pymysql.connect(host=dbConf.DB_HOST, user=dbConf.DB_USERNAME, passwd=dbConf.DB_PASSWORD, db=dbConf.DB_DATABASE, charset='utf8')
        self.cursor = self.db.cursor(cursor=pymysql.cursors.DictCursor)
    
    def table(self, table_name):
        self.table_name = table_name
        return self

    def inster(self, fields = {}):
        fields_name = []
        fields_value = []
        for k in fields.keys():
            fields_name.append(k)
            fields_value.append("'"+str(fields[k])+"'")

        
        fields_name_str = ','.join(fields_name)
        fields_value_str = ','.join(fields_value)
        sql = """INSERT INTO """+ self.table_name +""" ("""+ fields_name_str+ """) VALUES ("""+ fields_value_str +""")"""

        # print(sql)
        self.cursor.execute(sql)

        self.db.commit()

        lastId = self.cursor.lastrowid

        return lastId
    
    def select(self, where= "1=1", fields='*'):

        if self.where_str !='':
            where = self.where_str
        
        if self.fields_str != '':
            fields = self.fields_str

        self.sql = "select "+fields+" from "+self.table_name+" where "+ where

        return self

    #查询一条数据
    def find(self):
        
        if self.sql == '': self.select()

        self.cursor.execute(self.sql)
        res = self.cursor.fetchone()
        return res
    
    def all(self):
        # print('执行查询')
        self.cursor.execute(self.sql)
        res = self.cursor.fetchall()

        return res

    def where(self, where):
        self.where_str = where
        return self
    
    def fields(self, fields_str):
        if fields_str : self.fields_str = fields_str
        return self
    
    def update(self, fields = {}):
        array = []
        for k in fields.keys():
            string = k + "='"+str(fields[k])+"'"
            array.append(string)

        updateData = ','.join(array)

        sql = "UPDATE "+self.table_name+" SET "+updateData

        if self.where_str:
            sql += " WHERE "+ self.where_str
        

        # print(sql)

        self.cursor.execute(sql)

        self.db.commit()

        return True

    
    def __del__(self):#析构函数
         #关闭游标
        self.cursor.close()
         #关闭数据库
        self.db.close()
        # print('关闭数据库')

    # def __enter__(self):
    #     return self
    
    # def __exit__(self,exc_type, exc_val, exc_tb):
    #     #执行ｓｑｌ
    #     self.db.commit()
    #     #关闭游标
    #     #self.cursor.close()
    #     #关闭数据库
    #     self.db.close()


# a = Db().table('singers').select().all()
# print(a)
# if a is not None:
#     print(a)
# else:
#     print(111)
# t = tool.getCurrDate()
# lastId = Db().table('singers').inster({'name':'黎明','created_at':t})
# print(lastId)